<template>
  <div class=".draw-control">
    <div ref="drawList" v-show="drawListVisible" class="draw-list">

      <div class="draw-list-title" ref="drawListTitle">
        我的标绘<i class="el-icon-close" title="关闭" @click="drawListVisible = false"></i>
      </div>

      <div class="draw-list-tab">
        <a @click="currentTab = 'marker'"
           :class="'draw-list-tab-item ' + (currentTab === 'marker' ? 'draw-list-tab-item-active' : '')"><img
          src="@static/css/images/draw/point.png" class="tab-icon"/></a>
        <a @click="currentTab = 'polyline'"
           :class="'draw-list-tab-item ' + (currentTab === 'polyline' ? 'draw-list-tab-item-active' : '')"><img
          src="@static/css/images/draw/line.png" class="tab-icon"/></a>
        <a @click="currentTab = 'circle'"
           :class="'draw-list-tab-item ' + (currentTab === 'circle' ? 'draw-list-tab-item-active' : '')"><img
          src="@static/css/images/draw/circle.png" class="tab-icon"/></a>
        <a @click="currentTab = 'rectangle'"
           :class="'draw-list-tab-item ' + (currentTab === 'rectangle' ? 'draw-list-tab-item-active' : '')"><img
          src="@static/css/images/draw/rect.png" class="tab-icon"/></a>
        <a @click="currentTab = 'polygon'"
           :class="'draw-list-tab-item ' + (currentTab === 'polygon' ? 'draw-list-tab-item-active' : '')"><img
          src="@static/css/images/draw/ploygon.png" class="tab-icon"/></a>
      </div>

      <div class="draw-list-list">
        <div class="draw-list-list-row" v-for="(item, index) in custLayerArray.filter(o => o.type === currentTab)"
             :key="item.key">
          <span>{{index + 1}}. {{item.name}}</span>
          <i class="el-icon-map-location" title="定位" @click="viewLayerLocationById(item.id)"/>
          <i class="el-icon-edit-outline" title="编辑" @click="editLayerById(item.id)"/>
          <i class="el-icon-delete" title="删除" @click="deleteLayerById(item.id)"/>
        </div>
        <div v-if="!custLayerArray.filter(o => o.type === currentTab).length" class="draw-list-empty">
          空空如也，<a style="color:#3a8ee6" @click="addLayer(currentTab)">新建一个</a>
        </div>
        <a class="add-layer" @click="addLayer(currentTab)" v-else>
          <i class="el-icon-plus" title="新增" style="align-self:center;"/>
        </a>
      </div>
    </div>

    <!-- 标绘编辑与新建窗口 -->
    <div ref="layerEditContainer" v-show="layerEditDialogVisible" class="layer-edit-container">
      <div ref="layerEditTitle" class="layer-edit-title"><span>{{editDataCache.title}}</span></div>
      <div class="layer-edit-name-row">
        <span>名称</span>
        <el-input v-model="editDataCache.name" placeholder="输入名称" class="layer-edit-input-name"></el-input>
      </div>
      <div v-for="(dms, index) in editDataCache.dmsArray" :key="dms.key">
        <LatLng
          :dms="dms.dmsString"
          :type="editDataCache.type"
          :index="index"
          :count="editDataCache.dmsArray.length"
          @onLocationChange="layerEditLocationChanged"
          @onLatLngDelete="layerEditDeleteLatLng"
        ></LatLng>
      </div>
      <a class="add-latlng" v-if="editDataCache.type === 'polyline' || editDataCache.type === 'polygon'"
         @click="addLatLngToLayer()">
        <i class="el-icon-plus" title="新增坐标" style="align-self:center;"/>
      </a>
      <div v-if="editDataCache.type === 'circle'" class="layer-edit-radius-row">
        <span>半径</span>
        <el-input v-model="editDataRadiusInNM" placeholder="输入半径" class="layer-edit-input-name"
                  @change="editDataCache.changed = true"></el-input>
        <span> 海里</span>
      </div>
      <div style="padding:10px;display:flex;flex-direction:row;justify-content: center;align-items:center;">
        <el-button type="primary" @click="cancelLayerEdit" style="padding: 5px 10px;">取 消</el-button>
        <el-button type="primary" @click="confirmLayerEdit" style="padding: 5px 10px;">保 存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import drawHelper from './DrawLib'
  import drag from '@/utils/drag'
  import LatLng from './LatLng'

  import {
    stringToLatlng,
    latlngToString,
    meters2nm,
    nm2meters,
    dmsToLatLng,
    latlngToDmsString
  } from '@/utils/latlngUtil';

  const nextKey = (function () {
    let idx = 0
    return function () {
      idx++
      return idx
    }
  })()
  const shapeOptions = {
    color: '#ff0000',
    weight: 2,
    fillColor: '#ff0000'
  }

  const MyCustomMarker = L.Icon.extend({
    options: {
      shadowUrl: null,
      iconAnchor: new L.Point(13, 41),
      iconSize: new L.Point(25, 41),
      popupAnchor: [-1, -30],
      iconUrl: '../../../../static/css/images/marker-icon.png'
    }
  });

  export default {
    components: {
      LatLng
    },
    props: ['map'],
    name: 'DrawControl',
    watch: {
      map: {
        deep: false,
        handler (newMap, oldMap) {
          if (!newMap.DrawControlLoaded) {
            // console.log('reload map.......')
            this.initControl()
          }
        }
      }
    },
    data() {
      return {
        drawListVisible: false,
        layerEditDialogVisible: false,
        custLayerArray: [],
        currentTab: 'marker',
        editDataCache: {},
        editDataRadiusInNM: '',
        layerEditMode: false,
        drawObject: [],
        drawOptions: {
          position: 'topright',
          edit: {
            poly: {
              allowIntersection: false
            }
          },
          draw: {
            marker: {
              icon: new MyCustomMarker()
            },
            circlemarker: false,
            polygon: {
              allowIntersection: false,
              showArea: true,
              showLength: true,
              nautic: true,
              metric: false,
              feet: false,
              precision: {nm: 2, km: 2},
              ...shapeOptions
            },
            polyline: {
              nautic: true,
              metric: false,
              feet: false,
              shapeOptions: {
                ...shapeOptions,
                weight: 3
              }
            },
            circle: {
              nautic: true,
              metric: false,
              feet: false,
              shapeOptions
            },
            rectangle: {
              metric: ['km'],
              precision: {km: 2},
              shapeOptions
            }
          }
        }
      }
    },
    mounted() {
      // console.log('mount this is::::', this.map)
      this.initControl()
      this.loadCustomLayer()
    },
    methods: {
      saveCustomLayer () {
        // console.log('save.....', this.custLayerArray, this.drawObject);
        let arrayToSave = this.custLayerArray.map(layer => {
          // console.log('save one layer*******************', layer)
          let obj = this.drawObject.find(o => {
            // console.log('find........', o._leaflet_id, layer.id)
            return o._leaflet_id === layer.id;
          })
          let latlngs = null
          if (layer.type === 'marker' || layer.type === 'circle') {
            latlngs = [obj.getLatLng()]
          } else if (layer.type === 'polygon' || layer.type === 'rectangle') {
            latlngs = obj.getLatLngs()[0]
          } else {
            latlngs = obj.getLatLngs()
          }
          return {
            name: layer.name,
            type: layer.type,
            latlngs,
            radius: obj.getRadius ? obj.getRadius() : undefined
          }
        })
        localStorage.setItem('customDraw', JSON.stringify(arrayToSave))
      },
      loadCustomLayer () {
        let savedLayers = localStorage.getItem('customDraw')
        if (savedLayers) {
          let ary = JSON.parse(savedLayers)
          ary.forEach(o => {
            // console.log('load one layer:::::', o)
            let layer = drawHelper.drawLayer(o)
            layer.name = o.name
            layer.layerType = o.type
            this.drawObject.push(layer)
            o.id = layer._leaflet_id
            this.custLayerArray.push(o)
            if (o.radius) {
              o.radiusInNM = 1.0 * parseInt(o.radius / 1852 * 100) / 100
            }
            // console.log('oooooo', o)
            this.addPopupForLayer(o, layer)
          })
        }
      },
      initControl () {
        this.map.DrawControlLoaded = true
        // 拖拽
        drag(this.$refs.drawListTitle, this.$refs.drawList)
        drag(this.$refs.layerEditTitle, this.$refs.layerEditContainer)
        /* 绘制工具条 start */
        let drawnItems = L.featureGroup().addTo(this.map)
        this.drawOptions.edit.featureGroup = drawnItems
        this.drawOptions.draw.list = {
          icon: 'el-icon-notebook-2',
          click: () => {
            this.drawListVisible = !this.drawListVisible
          }
        }

        drawHelper.setDrawLayer(drawnItems)
        let drawControl = new L.Control.Draw(this.drawOptions)
        this.drawControl = drawControl
        this.map.addControl(drawControl)

        // 所有绘制的对象
        this.map.on(L.Draw.Event.CREATED, event => {
          // console.log(event.layer, event);
          drawnItems.addLayer(event.layer)
          this.drawLayerCreated(event)
        })

        this.map.on(L.Draw.Event.EDITED, this.drawLayerUpdated)
        this.map.on(L.Draw.Event.DELETED, this.drawLayerDeleted)
        this.map.on(L.Draw.Event.DRAWSTART, e => {
          // console.log('draw start==========::::::::', e.layerType);
          if (e.layerType === 'marker') {
            this.addLayer('marker')
          } else {
            this.layerEditDialogVisible = false
          }
        })
        this.map.on(L.Draw.Event.DRAWSTOP, e => {
          // console.log('draw stop::::::::', e.layerType);
          if (!this.layerEditMode) {
            this.layerEditDialogVisible = false
          }
        })
        this.map.on(L.Draw.Event.DRAWVERTEX, e => {
          // console.log('draw vertex:', e)
        })

        /* 绘制工具条 end */
      },
      drawLayerCreated(event) {
        let {layerType, layer} = event;
        // console.log(layerType, layer);
        layer.layerType = layerType;
        this.drawObject.push(layer);

        let target = this.getTargetData(layer);

        if (layer.name) {
          target.name = layer.name;
        } else {
          if (target.type === 'marker' || target.type === 'circlemarker') {
            // obj.typeName = '标记点';
            target.name = '标记点';
          } else if (target.type === 'polyline') {
            // obj.typeName = '折线';
            target.name = '折线';
          } else if (target.type === 'polygon') {
            // obj.typeName = '多边形';
            target.name = '多边形';
          } else if (target.type === 'rectangle') {
            // obj.typeName = '矩形';
            target.name = '矩形';
          } else if (target.type === 'circle') {
            // obj.typeName = '圆形';
            target.name = '圆形';
          }
        }

        target.key = nextKey();
        // console.log('layer changed........', target[0]);
        this.addPopupForLayer(target, layer);
        this.custLayerArray.push(target);
        this.saveCustomLayer()
      },
      drawLayerUpdated (event) {
        let layers = event.layers
        let targetAry = []
        layers.eachLayer(layer => {
          let target = this.getTargetData(layer)
          targetAry.push(target)
        })
        this.layerChanged('update', targetAry);
      },
      drawLayerDeleted(event) {
        let layers = event.layers;
        let targetAry = [];
        layers.eachLayer(layer => {
          let idx = this.drawObject.findIndex(obj => obj._leaflet_id === layer._leaflet_id);
          this.drawObject.splice(idx, 1);

          let target = this.getTargetData(layer);
          targetAry.push(target);
        })
        this.layerChanged('delete', targetAry);
      },
      viewLayerLocationById(id) {
        let layer = this.drawObject.find(obj => obj._leaflet_id === id);
        if (layer.getBound) {
          this.map.fitBounds(layer.getBounds());
        } else if (layer._bounds) {
          this.map.fitBounds(layer._bounds);
        } else if (layer.getLatLng) {
          this.map.setView(layer.getLatLng());
        } else {
          console.log('do not know how to show layer at point for:', layer);
        }
        layer.openPopup()
      },
      editLayerById (id) {
// 修改前先定位
        this.showLayerAtMapById(id);
        // console.log('editLayerById:this.custLayerArray::::', this, id, this.custLayerArray);
        let uiData = this.custLayerArray.find(obj => obj.id === id);
        let data = this.getLayerDataById(id);
        this.layerEditMode = true;
        this.clearEditCache();
// console.log('edit layer:::', uiData, data);
        let title = '编辑';
        if (data.type === 'marker') {
          title += '坐标点';
        } else if (data.type === 'polyline') {
          title += '折线';
        } else if (data.type === 'polygon') {
          title += '多边形';
        } else if (data.type === 'rectangle') {
          title += '矩形';
        } else if (data.type === 'circle') {
          title += '圆形';
          this.editDataRadiusInNM = meters2nm(data.radiusInMeters);
        }

        this.editDataCache = {
          id: data.id,
          title,
          type: data.type,
          name: uiData.name,
          dmsArray: data.latlngs.map(o => {
            return {
              key: nextKey(),
              dmsString: latlngToDmsString(o.lat, o.lng)
            }
          })
        };
        this.layerEditDialogVisible = true;
      },
      deleteLayerById (id) {
        this.removeLayerById(id);
        let idx = this.custLayerArray.findIndex(o => o.id === id);
        this.custLayerArray.splice(idx, 1);
        if (this.editDataCache.id === id) {
          this.layerEditDialogVisible = false;
        }
        this.saveCustomLayer()
      },
      cancelLayerEdit() {
        this.layerEditDialogVisible = false
        if (this.drawControl._toolbars.draw._activeMode) {
          this.drawControl._toolbars.draw._activeMode.handler.disable()
        }
      },
      confirmLayerEdit() {
        if (!this.editDataCache.name) {
          this.$alert('请输入标绘名称');
          return;
        }

        this.editDataCache.latlngs = [];
        for (let i = 0; i < this.editDataCache.dmsArray.length; i++) {
          let latlng = this.checkDms(this.editDataCache.dmsArray[i].dmsString);
          if (latlng.error) {
            return this.$alert(`第${i + 1}个坐标：${latlng.error}`);
          }
          this.editDataCache.latlngs.push(latlng);
        }

        if (this.editDataCache.type === 'circle') {
          if (isNaN(parseInt(this.editDataRadiusInNM)) || this.editDataRadiusInNM <= 0) {
            return this.$alert('请正确输入圆形半径');
          }
        }

        if (!this.layerEditMode) {
          // 新建模式，生成对象
          this.drawLayerObject({
            name: this.editDataCache.name,
            type: this.editDataCache.type,
            latlngs: this.editDataCache.latlngs,
            radiusInMeters: nm2meters(this.editDataRadiusInNM)
          });
        } else {
          let layer = null;
          if (this.editDataCache.type === 'marker' || this.editDataCache.type === 'circlemarker') {
            layer = this.setLayerProperty(this.editDataCache.id, this.editDataCache.latlngs[0]);

          } else if (this.editDataCache.type === 'polyline' || this.editDataCache.type === 'polygon' || this.editDataCache.type === 'rectangle') {
            layer = this.setLayerProperty(this.editDataCache.id, this.editDataCache.latlngs);

          } else if (this.editDataCache.type === 'circle') {
            // console.log('ready set layer:::::', this.editDataCache);
            layer = this.setLayerProperty(this.editDataCache.id, {
              center: this.editDataCache.latlngs[0],
              radiusInMeters: nm2meters(this.editDataRadiusInNM)
            });

          }
          // 更新完成后需要将数据写回到列表中
          // this.custLayerArray.find(obj => obj.id === this.editDataCache.id);
          let data = this.custLayerArray.find(o => o.id === this.editDataCache.id);
          data.name = this.editDataCache.name;
          let target = this.getLayerDataById(this.editDataCache.id);
          target.name = data.name;
          //target.latlngs = this.editDataCache.changedLatLngs;
          //target.radius = this.editDataRadiusInNM;
          this.addPopupForLayer(target, layer);
        }

        this.layerEditDialogVisible = false
        this.saveCustomLayer()
      },
      layerEditLocationChanged (data) {
        this.editDataCache.dmsArray[data.index].dmsString = data.dms;
      },
      layerEditDeleteLatLng (idx) {
        this.editDataCache.dmsArray.splice(idx, 1)
      },
      // 标绘发生变化
      layerChanged (action, target, layer) {
        console.log('layer changed::::', action, layer, target);
        if (action === 'create') {
          let obj = {id: target[0].id, type: target[0].type};
          if (layer.name) {
            obj.name = layer.name;
          } else {
            if (obj.type === 'marker' || obj.type === 'circlemarker') {
              // obj.typeName = '标记点';
              obj.name = '标记点';
            } else if (obj.type === 'polyline') {
              // obj.typeName = '折线';
              obj.name = '折线';
            } else if (obj.type === 'polygon') {
              // obj.typeName = '多边形';
              obj.name = '多边形';
            } else if (obj.type === 'rectangle') {
              // obj.typeName = '矩形';
              obj.name = '矩形';
            } else if (obj.type === 'circle') {
              // obj.typeName = '圆形';
              obj.name = '圆形';
            }
          }

          target[0].name = obj.name;
          obj.key = nextKey();
          // console.log('layer changed........', target[0]);
          this.addPopupForLayer(target[0], layer);
          this.custLayerArray.push(obj);
          // console.log('layerChanged::::this.custLayerArray:::::', this, this.custLayerArray);
        } else if (action === 'delete') {
          target.forEach(o => {
            let idx = this.custLayerArray.findIndex(item => item.id === o.id);
            this.custLayerArray.splice(idx, 1);
          });
        } else if (action === 'update') {
          debugger
          target.forEach(o => {
            this.addPopupForLayer(o, this.drawObject.find(l => l._leaflet_id === o.id))
          })
        }
        this.saveCustomLayer()
      },
      // 新增标绘
      addLayer (type) {
        this.layerEditMode = false;
        let title = '新建';
        let ptCount = 0;
        // 度分表
        let dmsArray = [];
        // let changedDms = null;
        if (type === 'marker') {
          title += '坐标点';
          ptCount = 1;
          // changedDms = [''];
        } else if (type === 'polyline') {
          title += '折线';
          ptCount = 2;
          // changedDms = ['',''];
        } else if (type === 'polygon') {
          title += '多边形';
          ptCount = 3;
          // changedDms = ['','',''];
        } else if (type === 'rectangle') {
          title += '矩形';
          ptCount = 2;
          // changedDms = ['',''];
        } else if (type === 'circle') {
          title += '圆形';
          ptCount = 1;
          // changedDms = [''];
        }
        let mary = [
          '38,0,0,121,0,10',
          '38,20,0,121,10,0',
          '37,10,0,121,20,0',
          '37,50,0,121,20,0',
          '37,50,0,121,5,0'
        ];
        for (let i = 0; i < ptCount; i++) {
          dmsArray.push({
            dmsString: mary[i],
            key: nextKey()
          })
        }
        // console.log('dmsary:', dmsArray);
        this.editDataCache = {
          title,
          type: this.currentTab,
          name: '',
          dmsArray
        };
        if (this.currentTab === 'circle') {
          this.editDataRadiusInNM = '';
        }

        this.layerEditDialogVisible = true;
      },
      addPopupForLayer(obj, layer) {
        // console.log('add popup for layer::::', obj, layer)
        if (!window.popupDeleteClick) {
          window.popupDeleteClick = this.deleteLayerById.bind(this);
          window.popupEditClick = this.editLayerById.bind(this);
        }
        // console.log('....this.custLayerArray::::', this.custLayerArray, obj);
        let html = '<div class="layer-pop-container">';
        html += '<div class="layer-pop-title">' + (obj.name || layer.name) + '</div>';

        let latlng = latlngToString({lat: obj.latlngs[0].lat, lng: obj.latlngs[0].lng});
        if (obj.type === 'marker' || obj.type === 'circlemarker') {
          html += '<div class="layer-pop-latlng-row"><span>坐标：' + latlng.lat.text + 'N</span> : <span>' + latlng.lng.text + 'E</span></div>';
        } else if (obj.type === 'polyline') {
          // 计算长度
          let distance = 0;
          for (let i = 0; i < obj.latlngs.length - 1; i++) {
            distance += this.map.distance(obj.latlngs[i], obj.latlngs[i + 1]);
          }
          html += '<div class="layer-pop-latlng-row"><span>总长度：' + (Math.round(distance / 1852 * 100) / 100) + ' 海里</span></div>';
        } else if (obj.type === 'polygon') {
          // 计算面积、周长
          let distance = 0;
          for (let i = 0; i < obj.latlngs.length - 1; i++) {
            distance += this.map.distance(obj.latlngs[i], obj.latlngs[i + 1]);
          }
          distance += this.map.distance(obj.latlngs[0], obj.latlngs[obj.latlngs.length - 1]);
          let area = L.GeometryUtil.geodesicArea(obj.latlngs)
          html += '<div class="layer-pop-latlng-row"><span>周长：' + (Math.round(distance / 1852 * 100) / 100) + ' 海里</span></div>';
          html += '<div class="layer-pop-latlng-row"><span>面积：' + (Math.round(area / 10000) / 100) + ' 平方公里</span></div>';
        } else if (obj.type === 'rectangle') {
          let southEast = {lat: obj.latlngs[0].lat, lng: obj.latlngs[1].lng};
          let width = this.map.distance(obj.latlngs[0], southEast);
          let height = this.map.distance(obj.latlngs[1], southEast);
          let length = (width + height) * 2;
          let sq = width * height;
          html += '<div class="layer-pop-latlng-row"><span>周长：' + (Math.round(length / 1852 * 100) / 100) + ' 海里</span></div>';
          html += '<div class="layer-pop-latlng-row"><span>面积：' + (Math.round(sq / 10000) / 100) + ' 平方公里</span></div>';
          // prefix = i === 0 ? '左下：' : '右上：';
        } else if (obj.type === 'circle') {
          html += '<div class="layer-pop-latlng-row"><span>中心：' + latlng.lat.text + 'N</span> : <span>' + latlng.lng.text + 'E</span></div>';
          html += '<div>半径：' + obj.radiusInNM + ' 海里</div>';
          html += '<div>面积：' + (Math.round(Math.PI * obj.radiusInNM * 1852 * obj.radiusInNM * 1852 / 10000) / 100) + ' 平方公里</div>';
          html += '<div>周长：' + (Math.round(Math.PI * 2 * obj.radiusInNM * 100) / 100) + ' 海里</div>';
        }

        html += '<div class="layer-pop-action-row"><a onclick="popupDeleteClick(' + obj.id + ')">删除</a> <a onclick="popupEditClick(' + obj.id + ')">编辑</a></div>';
        html += '</div>';
        // console.log('popup......', html);
        layer.bindPopup(html);
        //layer.openPopup();
      },
      getTargetData (layer) {
        let {layerType} = layer;
        let target = {
          id: layer._leaflet_id,
          type: layerType
        };
        if (layerType === 'marker' || layerType === 'circlemarker') {
          target.latlngs = [layer.getLatLng()];
        } else if (layerType === 'polyline') {
          target.latlngs = layer.editing.latlngs[0];
        } else if (layerType === 'polygon') {
          target.latlngs = layer.editing.latlngs[0][0];
        } else if (layerType === 'rectangle') {
          target.latlngs = [layer.getBounds().getSouthWest(), layer.getBounds().getNorthEast()];
        } else if (layerType === 'circle') {
          target.latlngs = [layer.getLatLng()];
          target.radiusInMeters = layer.getRadius();
          target.radiusInNM = meters2nm(target.radiusInMeters);
        }
        return target;
      },
      removeLayerById (id) {
        let idx = this.drawObject.findIndex(obj => obj._leaflet_id === id);
        let layer = this.drawObject[idx];
        this.drawObject.splice(idx, 1);
        layer.remove();
      },
      showLayerAtMapById (id) {
        let layer = this.drawObject.find(obj => obj._leaflet_id === id);
        if (layer.getBound) {
          this.map.fitBounds(layer.getBounds());
        } else if (layer._bounds) {
          this.map.fitBounds(layer._bounds);
        } else if (layer.getLatLng) {
          this.map.setView(layer.getLatLng());
        } else {
          console.log('do not know how to show layer at point for:', layer);
        }
        layer.openPopup();
      },
      clearEditCache() {
        this.editDataCache = {
          latlngs: []
        }
      },
      checkDms(dmsString) {
        let ary = dmsString.split(',');
        if (ary.length != 6) {
          return {error: '经纬度不正确'};
        }

        if (isNaN(parseInt(ary[0])) || isNaN(parseInt(ary[1])) || isNaN(parseInt(ary[2]))
          || isNaN(parseInt(ary[3])) || isNaN(parseInt(ary[4])) || isNaN(parseInt(ary[5]))) {
          return {error: '经纬度不正确'};
        }
        let d = Number(ary[0]);
        let m = Number(ary[1]);
        let s = Number(ary[2]);
        if (d < 0 || d > 90 || d != parseInt(d, 10)) {
          return {error: '纬度不正确'};
        } else if (m < 0 || m > 59 || m != parseInt(m, 10)) {
          return {error: '纬度不正确'};
        } else if (s < 0 || s > 60) {
          return {error: '纬度不正确'};
        }
        let lat = dmsToLatLng(d, m, s);

        d = Number(ary[3]);
        m = Number(ary[4]);
        s = Number(ary[5]);
        if (d < 0 || d > 180 || d != parseInt(d, 10)) {
          return {error: '经度不正确'};
        } else if (m < 0 || m > 59 || m != parseInt(m, 10)) {
          return {error: '经度不正确'};
        } else if (s < 0 || s > 60) {
          return {error: '经度不正确'};
        }
        let lng = dmsToLatLng(d, m, s);
        return {lat, lng};
      },
      drawLayerObject (data) {
        // console.log('drawLayerObject:', data);
        let e = {layerType: data.type};
        if (data.type === 'marker') {
          let latlng = data.latlngs[0];
          e.layer = drawHelper.drawMarker(latlng);
        } else if (data.type === 'rectangle') {
          e.layer = drawHelper.drawRectangle(data.latlngs);
        } else if (data.type === 'polyline') {
          e.layer = drawHelper.drawPolyline(data.latlngs);
        } else if (data.type === 'polygon') {
          e.layer = drawHelper.drawPolygon(data.latlngs);
        } else if (data.type === 'circle') {
          // let radiusInMeters = nm2meters(data.radiusInMeters);
          e.layer = drawHelper.drawCircle(data.latlngs[0], data.radiusInMeters);
        }
        e.layer.name = data.name;
        this.drawLayerCreated(e);
        // 结束从工具条开始的绘制
        this.cancelLeafletDraw();
      },
      setLayerProperty (id, data) {
        let layer = this.drawObject.find(obj => obj._leaflet_id === id);
        console.log('set layer:', layer, data);
        if (layer.layerType === 'marker' || layer.layerType === 'circlemarker') {
          layer.setLatLng(data);
          return layer;
        } else if (layer.layerType === 'polyline' || layer.layerType === 'polygon') {
          layer.setLatLngs(data);
          return layer;
        } else if (layer.layerType === 'rectangle') {
          let bounds = L.latLngBounds(data);
          layer.setBounds(bounds);
          return layer;
        } else if (layer.layerType === 'circle') {
          return layer.setRadius(data.radiusInMeters).setLatLng(data.center);
        }
      },
      cancelLeafletDraw () {
        if (this.drawControl._toolbars.draw._activeMode) {
          this.drawControl._toolbars.draw._activeMode.handler.disable();
        }
      },
      getLayerDataById (id) {
        let layer = this.drawObject.find(obj => obj._leaflet_id === id)
        return this.getTargetData(layer)
      }
    }
  }
</script>

<style>
  @import '../../../../static/js/draw-lib/leaflet.draw.css';

  /* 工具条淡入淡出 */
  @-webkit-keyframes hideToolbar {
    from {
      height: 220px;
    }
    to {
      height: 30px;
    }
  }

  @-webkit-keyframes showToolbar {
    from {
      height: 30px;
    }
    to {
      height: 220px;
    }
  }

  .leaflet-toolbar-hide {
    animation: hideToolbar 0.2s;
    animation-fill-mode: forwards;
    overflow: hidden;
  }

  .leaflet-toolbar-show {
    animation: showToolbar 0.2s;
    animation-fill-mode: forwards;
    overflow: hidden;

  }
</style>

<style lang="scss">
  /* 标绘对象popup样式 */
  .layer-pop-container {
    a {
      cursor: pointer;
    }

    .layer-pop-title {
      font-size: 14px;
      color: #3a8ee6;
      text-align: center;
    }

    .layer-pop-latlng-row {
      line-height: 20px;
    }

    .layer-pop-action-row {
      line-height: 25px;
      display: flex;
      justify-content: space-around;
    }
  }
  /* 标绘对象编辑窗口样式 */
  .layer-edit-container {

    position: absolute;
    right: 55px;
    top: 400px;
    z-index: 999;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);

    .add-latlng {
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-top:solid 1px #e9e9e9;
      border-bottom:solid 1px #e9e9e9;
    }

    .add-latlng:hover {
      background-color: #b3d8ff;
    }

    .layer-edit-title {
      font-size: 16px;
      line-height: 30px;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
      color: #fff;
      height: 30px;
      text-align: center;
      background-color: #0062cd;
      cursor: move;
      position: relative;

      i {
        position: absolute;
        top: 7px;
        right: 7px;
        cursor: pointer;
      }
    }

    .layer-edit-name-row {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px;
      border-bottom: solid 1px #e2e2e2;

      span {
        font-size: 12px;
        line-height: 30px;
        height: 30px;
      }

      .layer-edit-input-name {
        flex: 1;
        margin-left: 10px;

        input {
          height: 30px;
          line-height: 30px;
          padding: 0 10px;
        }
      }
    }

    .layer-edit-radius-row {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px;
      border-top: solid 1px #e2e2e2;

      span {
        font-size: 12px;
        line-height: 30px;
        height: 30px;
      }

      .layer-edit-input-name {
        flex: 1;
        margin-left: 10px;

        input {
          height: 30px;
          line-height: 30px;
          padding: 0 10px;
        }
      }
    }
  }

  /* 标绘列表样式 */
  .draw-list {
    position: absolute;
    top: 20px;
    right: 55px;
    width: 300px;
    max-height: 500px;
    overflow-y: auto;
    z-index: 999;
    box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);

    .draw-list-title {
      font-size: 16px;
      line-height: 30px;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
      color: #fff;
      height: 30px;
      text-align: center;
      background-color: #0062cd;
      cursor: move;
      position: relative;

      i {
        position: absolute;
        top: 7px;
        right: 7px;
        cursor: pointer;
      }
    }

    .tab-icon {
      width: 25px;
      height: 25px;
      object-fit: contain;
    }

    .draw-list-tab {
      display: flex;
      flex-direction: row;

      .draw-list-tab-item {
        flex: 1;
        padding: 6px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #e9e9e9;
      }

      .draw-list-tab-item-active {
        background-color: #fff;
      }
    }

    .draw-list-list {
      display: flex;
      flex-direction: column;
      min-height: 300px;
      background-color: #fff;

      .draw-list-empty {
        height: 100%;
        color: #ccc;
        flex: 1;
        font-size: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .add-layer {
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .add-layer:hover {
        background-color: #b3d8ff;
      }

      .draw-list-list-row {
        padding: 5px 10px;
        display: flex;
        flex-direction: row;
        height: 20px;
        align-items: center;
        border-bottom: solid 1px #e9e9e9;

        span {
          font-size: 14px;
          text-align: left;
          flex: 1;
        }

        i {
          font-weight: normal;
          margin-left: 10px;
          cursor: pointer;
        }
      }

      .draw-list-list-row:nth-child(even) {
        background-color: #f2f2f2;
      }
    }


  }
</style>
